package com.unitd.frame.comm.serializer.impl;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.unitd.frame.comm.serializer.ISerializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @desc 使用 Kryo 实现序列化
 * @filename KryoSerializer.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2017/02/19
 */
public class KryoSerializer implements ISerializer {

	private final static Kryo kryo = new Kryo();

	/**
	 * @desc 获取序列化类型名称
	 * @return
	 */
	@Override
	public String name() {
		return "kryo";
	}

	/**
	 * @desc 序列化指定对象
	 * @param obj 需要序列化的对象
	 * @return
	 * @throws IOException
	 */
	@Override
	public byte[] serialize(Object obj) throws IOException {
		Output output = null;
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			output = new Output(baos);
			kryo.writeClassAndObject(output, obj);
			output.flush();
			return baos.toByteArray();
		} finally {
			if (output != null)
				output.close();
		}
	}

	/**
	 * @desc 反序列化指定对象
	 * @param bytes 需要反序列化的对象
	 * @return
	 * @throws IOException
	 */
	@Override
	public Object deserialize(byte[] bytes) throws IOException {
		if (bytes == null || bytes.length == 0)
			return null;
		Input ois = null;
		try {
			ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
			ois = new Input(bais);
			return kryo.readClassAndObject(ois);
		} finally {
			if (ois != null)
				ois.close();
		}
	}
}